package com.mspbots.teams.schedule;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mspbots.teams.model.TenantDTO;
import com.mspbots.teams.model.TriggerEventDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.mspbots.common.TriggerEvent.TEAMS_SCHEDULE;

/**
 * @author Dinnes Zhang
 * @date
 */
@Slf4j
@Component
public class MessageIncontrollable {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitMessagingTemplate messagingTemplate;

    private static final String REDIS_KEY_PREFIX_TENANT = "MSPBOTS:CONFIG:TENANT:";

//    @Scheduled(fixedRate = 2 * 60 * 1000)
    @Scheduled(fixedRateString = "${mspbots.fixedDelay.kill}")
    public void kill() {
        List tenants = redisTemplate.opsForList().range(REDIS_KEY_PREFIX_TENANT + "tenants", 0, -1);
        List<TenantDTO> tenantDTOS = objectMapper.convertValue(tenants, new TypeReference<List<TenantDTO>>() {});
        tenantDTOS.stream().filter(item -> item.getStatusId() == 1).forEach(tenantDTO -> {
            ObjectNode result = this.objectMapper.createObjectNode();
            result.put("tenantId",tenantDTO.getId());
            result.put("tenantName",tenantDTO.getName());
            TriggerEventDTO triggerEventDTO = new TriggerEventDTO();
            triggerEventDTO.setTenantId(tenantDTO.getId().longValue());
            triggerEventDTO.setEventName(TEAMS_SCHEDULE.getEvent());
            triggerEventDTO.setScope(TEAMS_SCHEDULE.getScope());
            triggerEventDTO.setPayload(result);
            this.messagingTemplate.convertAndSend("msp.trigger.event", "", triggerEventDTO);
        });
    }
}
